//
//  SegmentView.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/19.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

public protocol SegmentViewDelegate {
    
    // 到达城市点击
    func segment_stopCity()
    // 出发城市点击
    func segment_startCity()
    // 日期选择
    func segment_selectDate()
    // 航班搜索
    func segment_search(dict:NSDictionary,index:Int)
}

class SegmentView: UIView {
    
    // 背景图片
    private lazy var pic = UIImageView()
    // 点击按钮
    private lazy var btns = [UIButton]()
    // 切换背景UI
    private lazy var switchBackground =  UIView()
    
    // 航班号标题
    private lazy var flightTitle = UILabel(title: "航班号",color: COLOR_NICE,size: 12)
    // 航班号输入
    private lazy var inputFlightNum = InputTextView(title: "请输入航班号数字")
    
    // 出发日期标题
    private lazy var startDateTitle = UILabel(title: "出发日期",color: COLOR_NICE,size: 12)
    // 出发日期选择
    private lazy var startDateSelect = InputButtonView()
    // 出发日期箭头
    private lazy var rightArrow = UIImageView(image: UIImage(named: "arrow_12x12"))
    
    // 航班号标题
    private lazy var startCityTitle = UILabel(title: "出发城市",color: COLOR_NICE,size: 12)
    // 出发城市选择
    private lazy var startCity = InputButtonView()
    // 到达城市选择
    private lazy var stopCity = InputButtonView()
    // 到达城市标题
    private lazy var stopCityTitle = UILabel(title: "到达城市",color: COLOR_NICE,size: 12)
    
    // 切换城市
    private lazy var switchCity: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "flight_change_17x17"), for: .normal)
        return btn
    }()
    
    // 航班查询按钮
    private let orangeBtn = UIButton(title: "航班查询", name: "button_orange")
    
    // MARK: 代理
    public var delegate:SegmentViewDelegate?
    
    // MARK: 设置数据
    public var resetStartDate:String? {
        didSet {
            startDateSelect.setTitle(resetStartDate, for: .normal)
        }
    }
    
    public var resetStopCity:String? {
        didSet {
            stopCity.setTitle(resetStopCity, for: .normal)
        }
    }
    
    public var resetStartCity:String? {
        didSet {
            startCity.setTitle(resetStartCity, for: .normal)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        init_segment_views()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        init_segment_layout()
        init_switchui_layout()
    }
}

// MARK: 逻辑实现
extension SegmentView {
    
    // MARK: - TODO 航班查询
    @objc func filghtSearch() -> Void {
        let dict = NSMutableDictionary()
        if let input = inputFlightNum.text {
            dict["flightnumberid"] = input
        }
        if let start = startCity.titleLabel?.text ,pic.tag == 1{
            dict["city"] = start
        }
        if let stop = stopCity.titleLabel?.text ,pic.tag == 1{
            dict["endcity"] = stop
        }
        if let time = startDateSelect.currentTitle {
            dict["departdateall"] = time
        }
        if let time = startDateSelect.currentTitle?.split(separator: " ")[0]{
            dict["departdate"] = time
        }
        delegate?.segment_search(dict: dict,index: pic.tag)
    }
    
    // MARK: 日期选择
    @objc func clickSelectDate() -> Void {
        delegate?.segment_selectDate()
    }
    
    // MARK: 出发城市点击
    @objc func clickStartCity() -> Void {
        delegate?.segment_startCity()
    }
    
    // MARK: 到达城市点击
    @objc func clickStopCity() -> Void {
        delegate?.segment_stopCity()
    }
}

// MARK: - 布局实现
extension SegmentView {
    
    func isTwo() -> Bool {
        for item in subviews {
            for subitem in item.subviews {
                if subitem.contains(startCity) {
                    return true
                }
            }
        }
        return false
    }
    
    private func init_switchui_layout() -> Void {
        if isTwo() {
            let btn = UIButton()
            btn.tag = 2
            clickBtn(btn: btn)
        }else {
            init_one_way_layout()
        }
        // 不变的布局
        init_not_change()
    }
    
    // MARK: - 航班号布局
    func init_one_way_layout() -> Void {
        // 航班号标题
        flightTitle.frame = CGRect(x: MARGIN, y: MARGIN, width: MARGIN * 4, height: MARGIN)
        switchBackground.addSubview(flightTitle)
        // 航班号输入
        inputFlightNum.delegate = self
        let inputFlightNumY = flightTitle.frame.maxY
        inputFlightNum.frame = CGRect(x: MARGIN, y: inputFlightNumY, width: frame.width - MARGIN * 2, height: MARGIN50)
        switchBackground.addSubview(inputFlightNum)
    }
    
    // MARK: - 起降地布局
    func init_two_way_layout() -> Void {
        // 出发城市标题
        startCityTitle.frame = CGRect(x: MARGIN, y: MARGIN, width: MARGIN * 4, height: MARGIN)
        switchBackground.addSubview(startCityTitle)
        // 出发城市选择
        let cityW = (frame.width - MARGIN * 2) * 0.5
        startCity.setTitle("北京", for: .normal)
        startCity.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        startCity.frame = CGRect(x: MARGIN, y: flightTitle.frame.maxY, width: cityW, height: MARGIN50)
        switchBackground.addSubview(startCity)
        // 出发城市 添加监听事件
        startCity.addTarget(self, action: #selector(clickStartCity), for: .touchUpInside)
        
        // 切换图片
        let switchCityY = flightTitle.frame.maxY + MARGIN5
        switchCity.frame = CGRect(x: center.x - MARGIN40, y: switchCityY, width: MARGIN30, height: MARGIN30)
        switchBackground.addSubview(switchCity)
        // 切换图片 添加监听事件
        switchCity.addTarget(self, action: #selector(clickSwitchCity), for: .touchUpInside)
        
        // 到达城市标题
        stopCityTitle.textAlignment = .right
        let textWidth = stopCityTitle.text!.boundingRect(w: MARGIN * 4, h: MARGIN, fontSize: 12).width
        stopCityTitle.frame = CGRect(x: frame.width - MARGIN * 2 - textWidth, y: MARGIN, width: MARGIN * 4, height: MARGIN)
        switchBackground.addSubview(stopCityTitle)
        // 到达城市选择
        stopCity.alignment = .right
        stopCity.setTitle("上海", for: .normal)
        stopCity.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        stopCity.frame = CGRect(x: MARGIN + cityW, y: flightTitle.frame.maxY, width: cityW, height: MARGIN50)
        switchBackground.addSubview(stopCity)
        // 到达城市 添加监听事件
        stopCity.addTarget(self, action: #selector(clickStopCity), for: .touchUpInside)
    }
    
    private func init_not_change() -> Void {
        // 出发日期标题
        let startDateTitleY = flightTitle.frame.maxY + MARGIN20 + MARGIN50
        startDateTitle.frame = CGRect(x: MARGIN, y: startDateTitleY, width: MARGIN * 4, height: MARGIN)
        switchBackground.addSubview(startDateTitle)
        // 出发日期选择
        startDateSelect.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        let startDateSelectY = startDateTitle.frame.maxY
        startDateSelect.frame = CGRect(x: MARGIN, y: startDateSelectY, width: frame.width - MARGIN * 2, height: MARGIN50)
        startDateSelect.setTitle(AirLineUtil.shareInstance.getCurrentDate(), for: .normal)
        switchBackground.addSubview(startDateSelect)
        // 出发日期 添加监听事件
        startDateSelect.addTarget(self, action: #selector(clickSelectDate), for: .touchUpInside)
        // 出发日期箭头
        let rightArrowY = startDateTitle.frame.maxY + MARGIN
        rightArrow.frame = CGRect(x: frame.width - MARGIN * 2, y: rightArrowY, width: MARGIN, height:MARGIN)
        switchBackground.addSubview(rightArrow)
        
        // 航班查询按钮
        let orangeBtnY = startDateSelect.frame.maxY + MARGIN30
        orangeBtn.frame = CGRect(x: MARGIN, y: orangeBtnY, width:frame.width - MARGIN * 2, height: MARGIN * 3)
        switchBackground.addSubview(orangeBtn)
        // 航班查询 添加监听事件
        orangeBtn.addTarget(self, action: #selector(filghtSearch), for: .touchUpInside)
        
        // 设置背景
        switchBackground.layer.cornerRadius = 5
        switchBackground.backgroundColor = UIColor.white
        switchBackground.frame = CGRect(x: 0, y: pic.frame.maxY, width: frame.width, height: orangeBtn.frame.maxY + MARGIN30)
        addSubview(switchBackground)
    }
}

// MARK: - 代码不变
extension SegmentView {
    
    // MARK: - 切换城市点击
    @objc func clickSwitchCity() -> Void {
        guard let start = startCity.titleLabel?.text else {
            return
        }
        guard let stop = stopCity.titleLabel?.text else {
            return
        }
        stopCity.setTitle(start, for: .normal)
        startCity.setTitle(stop, for: .normal)
    }
    
    // MARK: - 切换布局
    @objc func clickBtn(btn:UIButton) -> Void {
        switch btn.tag {
        case 1:
            switch_to_one_way()
        case 2:
            switch_to_two_way()
        default:
            break
        }
    }
    
    // MARK: - 切到按航班号布局
    private func switch_to_one_way() -> Void {
        btns[0].setTitleColor(COLOR_NICE, for: .normal)
        btns[1].setTitleColor(UIColor.white, for: .normal)
        pic.image = UIImage(named: "segment_one_way")
        pic.tag = 0
        // 切到按航班号视图
        stopCity.removeFromSuperview()
        startCity.removeFromSuperview()
        switchCity.removeFromSuperview()
        stopCityTitle.removeFromSuperview()
        startCityTitle.removeFromSuperview()
        inputFlightNum.removeFromSuperview()
        // 添加新试图
        init_one_way_layout()
    }
    
    // MARK: - 切到按起降地布局
    private func switch_to_two_way() -> Void {
        btns[1].setTitleColor(COLOR_NICE, for: .normal)
        btns[0].setTitleColor(UIColor.white, for: .normal)
        pic.image = UIImage(named: "segment_two_way")
        pic.tag = 1
        // 切到按起降地视图
        flightTitle.removeFromSuperview()
        inputFlightNum.removeFromSuperview()
        inputFlightNum.text = nil
        // 添加新试图
        init_two_way_layout()
    }
}

// MARK: - 切换背景图片初始化
extension SegmentView {
    
    private func init_segment_views() -> Void {
        // 背景图片
        addSubview(pic)
        // 点击按钮
        for i in 1...2 {
            let btn = UIButton()
            btn.tag = i
            btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
            btn.addTarget(self, action: #selector(clickBtn(btn:)), for: .touchUpInside)
            btns.append(btn)
            addSubview(btn)
        }
    }
    
    private func init_segment_layout() -> Void {
        // 背景图片
        pic.tag = 0
        pic.image = UIImage(named: "segment_one_way")
        pic.frame = CGRect(x: 0, y: 0, width: frame.width, height: MARGIN50)
        // 按航班号
        let btn0 = btns[0]
        btn0.setTitle("按航班号", for: .normal)
        btn0.setTitleColor(COLOR_NICE, for: .normal)
        btn0.frame = CGRect(x: 0, y: 0, width: frame.width * 0.5, height: MARGIN50)
        // 按起降地
        let btn1 = btns[1]
        btn1.setTitle("按起降地", for: .normal)
        btn1.setTitleColor(UIColor.white, for: .normal)
        btn1.frame = CGRect(x: frame.width * 0.5, y: 0, width: frame.width * 0.5, height: MARGIN50)
    }
}

// MARK: - 隐藏键盘
extension SegmentView: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 隐藏键盘
        endEditing(true)
        // 完成输入
        return true
    }
}
